<template>
  <div class="login">
    <p class="login_title">登录</p>
    <van-form @submit="onSubmit">
      <van-field v-model="user" name="邮箱" label="邮箱" />
      <van-field v-model="passWord" type="passWord" name="密码" label="密码" />
      <router-link class="register" to="register">还没有账号?注册></router-link>
      <div style="margin: 16px">
        <van-button round block type="info" color="#ff690c" native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
let rep_email =
  /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
import { Dialog } from "vant";
import { loginFunc } from "@/http/request.js";

export default {
  data() {
    return {
      user: "",
      passWord: "",
    };
  },
  methods: {
    // 请求服务器处理登录
    onSubmit() {
      // 执行登录的函数
      this.login(this.user, this.passWord);
    },
    // 登录
    login(user, passWord) {
      // 执行登录的API
      loginFunc("/user/login", {
        user,
        passWord,
      }).then((data) => {
        // 登录成功
        // let { data } = data;
        // console.log(data);
        if (data.code == 200) {
          // 解构赋值
          let { token, email, userName, avatar, id } = data;
          // 把用户的临时身份储存在本地(可以把token进行切片之后储存起来,需要使用再进行拼接)
          // localStorage.setItem("token", token);
          // 把数据储存在vuex
          // console.log(this.$store);
          this.$store.dispatch("user/setEmailAsync", email);
          // this.$store.dispatch("user/setPhoneAsync", phone);
          this.$store.dispatch("user/setAvatarAsync", avatar);
          this.$store.dispatch("user/setUserNameAsync", userName);
          this.$store.dispatch("user/setIdAsync", id);
          Dialog.alert({
            title: "是否跳转个人中心页面?",
            message: data.msg,
          }).then(() => {
            // 页面跳转(传递参数)
            this.$router.push({
              name: "my",
              params: { email, userName },
            });
          });
        } else {
          Dialog.alert({
            title: "账号或密码错误",
            // message: ,
          });
        }
      });
    },
  },
};
</script>

<style lang='scss' scoped>
@import "@/static/common/base.scss";
.login {
  padding: $p;
  background-color: #eee;
  position: fixed;
  width: 100%;
  height: 100%;

  .login_title {
    text-align: center;
    height: 30vw;
    line-height: 30vw;
    font-size: 5.3333vw;
  }
  .register {
    text-align: right;
    font-size: 3.2vw;
    margin-top: 2vw;
    display: block;
  }
  .btn {
    margin-top: 20vw;
    width: 100%;
    button {
      width: 100%;
      background-color: $bgc;
      height: 10vw;
    }
  }
}
</style>